<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\Category;
use app\common\model\goods\Cart;
use app\common\model\MoneyLog;
use app\common\model\Order as ModelOrder;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order as OrderOrder;
use app\common\model\ScoreLog;
use app\common\model\server\Goods;
use app\common\model\server\Review;
use app\common\model\server\Type;
use app\common\model\User;
use app\common\model\user\Address;
use app\common\model\user\Level;
use app\server\GoodsServer;
use think\Db;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['lists'];
    protected $noNeedRight = ['*'];

    /**
     * 服务方式
     * @ApiMethod (GET)
     */
    public function lists()
    {
        $list = Type::all();
        $this->success('请求成功', $list);
    }

    /**
     * 下单
     * @ApiMethod (POST)
     * @param int $goods_id  商品id
     * @param int $num  商品数量
     * @param int $is_point  是否使用积分抵扣（0=不抵扣；1=抵扣）
     * @param int $type  （1=预下单；2=提交订单）
     * @param int $address_id  地址id
     * @param int $server_type  服务方式
     * @param int $add_type  下单方式（1=购物结算；2=立即下单）
     * 
     * 
     */
    public function addOrder()
    {
        $post = request()->post();
        extract($post);
        Db::startTrans();
        try {
            $userinfo = User::get($this->auth->id);
            $data['goods'] = Cart::getGoods($post, $userinfo->id, $add_type);
            // if ($type == 1) {
            //     $carts = Cart::list($userinfo->id);
            // } else {
            //     $cart_id = Cart::addCart([
            //         'goods_id' => $goods_id,
            //         'num' => $num,
            //         'type' => $type,
            //         'uid' => $userinfo->id,
            //     ]);
            //     $carts = collection(Cart::with('goods')->where('cart.id', $cart_id)->select())->toArray();
            // }

            //查询商品信息
            // $post['goods'] = Goods::get($goods_id);
            // if (!isset($goods_id) || !$goods_id || !$post['goods']) {
            //     exception('商品不存在');
            // }
            if (!isset($add_type) || !$add_type) {
                exception('下单方式错误');
            }
            // $data['level_id'] = $userinfo->level_id;
            $data['score'] = $userinfo->score;
            $data['user_id'] = $userinfo->id;
            $data['is_point'] = $is_point;
            $data['add_type'] = $add_type;
            $data['address_id'] = $address_id;

            $data = OrderOrder::yuOrder($data);
            if ($type == 2) {
                if (!isset($data['address_id']) || !$data['address_id']) {
                    exception('请选择地址');
                }
                if (!$server_type) {
                    exception('请选择服务方式');
                }
                $data['type'] = $server_type;
                $data['remark'] = $remark;
                $data = OrderOrder::addOrder($data);
                queue('app\common\job\Order', $data, 1800, 'order1246');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('', $data);
    }



    /**
     * 确认完成订单
     * @ApiMethod (POST)
     * @param int $order_id  订单id
     * 
     */
    public function completeOrder()
    {
        $post = request()->post();
        extract($post);
        if (!isset($order_id) || !$order_id) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = OrderOrder::get($order_id, ['user']);
            if (!$order) {
                exception('订单不存在');
            }
            if ($order->status != '20') {
                exception('订单状态错误');
            }
            $time = time();
            $order->taketime = $time;
            $order->status = '30';
            $order->save();
            //订单分佣
            MoneyLog::subcommission($order);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error('操作失败：' . $th->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 订单评论
     * @ApiMethod (POST)
     * @param int $order_id  订单id
     * @param array $data [{'goods_id':1,'description':'飒飒萨达'}]
     * 
     */
    public function reviewOrder()
    {
        $post = request()->post();
        extract($post);
        $rej = $this->validate(
            $post,
            [
                'order_id'  => 'require|gt:0',
                'data' => 'require',
            ]
        );
        if (true !== $rej) {
            $this->error($rej);
        }
        Db::startTrans();
        try {
            $order =  OrderOrder::get($order_id);
            if (!$order) {
                exception('订单不存在');
            }
            $order->status = '40';
            $order->save();
            foreach ($data as $v) {
                $review = new Review([
                    'description' => $v['description'],
                    'goods_id' => $v['goods_id'],
                    'user_id' => $order->user_id,
                    'order_id' => $order_id,
                ]);
                $review->save();
            }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error('操作失败：' . $th->getMessage());
        }
        $this->success('操作成功');
    }
    /**
     * @Author LK
     * @ApiTitle (订单列表)
     * @ApiMethod (GET)
     * @ApiParams (name="type", type="integer", required=true, sample="", description="all=全部，0=待付款,10=待服务,20=服务中,30=已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {
        $get = request()->get();
        extract($get);
        $order = new OrderOrder();

        if ($type == 'all') {
            $order->where('status', '<>', '-1');
        } elseif ($type == '30') {
            $order->whereIn('status', ['30', '40']);
        } else {
            $order->where('status', $type);
        }
        $list = $order->with(['info'])->where('user_id', $this->auth->id)->order('id desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->get();
        extract($param);
        $order = OrderOrder::get(['id' => $id], ['info']);
        $this->success('成功', $order);
    }


    /**
     * @Author LK
     * @ApiTitle (取消订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $param = request()->post();
        extract($param);
        $order = OrderOrder::get(['id' => $id, 'status' => 0]);
        if (!$order) {
            $this->error('订单错误');
        }
        Db::startTrans();
        try {
            $order->status = '-1';
            $order->canceltime = time();
            $order->save();
            if ($order['point'] > 0) {
                ScoreLog::income($order->user_id, $order->point, 1, 201, $order->sn);
            }
            $lists = OrderGoods::where('order_id', $order->id)->select();
            foreach ($lists as $v) {
                Goods::stockUp($v->goods_id, $v->goods_num);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
}
